package com.slt.developkitweb.controler.company;

import com.slt.developkitweb.vo.company.DecodeParameterVo;
import com.slt.developkitweb.annotation.ShowAPI;
import com.slt.developkitpersistent.model.EncryptDto;
import com.slt.developkitweb.util.CommonUtils;
import com.slt.developkitweb.util.Sns;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import static com.slt.developkitweb.util.test.AESUtils.*;

/**
 * @Author shalongteng
 * @Date 2023/8/31 9:39
 * @Description 解密中移金科网关，travelapi的数据。
 **/
@ShowAPI
@Api(tags = "商旅接口")
@RestController
@RequestMapping("/travel")
public class TravelDecryptController {

    @PostMapping("decryptGateway")
    @ApiOperation(value = "解密商旅网关数据")
    public String decryptGateway(@RequestBody EncryptDto encryptDto) {
        String encryptStr = encryptDto.getEncryptStr();
        encryptStr = encryptStr.replaceAll(" ", "+");
        return decrypt(encryptStr, "CBC");
    }

    @PostMapping("decryptGateway2")
    @ApiOperation(value = "解密商旅网关数据2")
    public String decryptGateway2(@RequestBody EncryptDto encryptDto) {
        String encryptStr = encryptDto.getEncryptStr();
        encryptStr = encryptStr.replaceAll(" ", "+");
        String decrypt = decrypt(encryptStr, "CBC");
        return decrypt(decrypt, "CBC");
    }

    @ApiOperation(value = "解密商旅参数")
    @PostMapping(value = "decodeParameter", produces = "application/json;charset=utf-8")
    public String decodeParameter(@RequestBody EncryptDto encryptDto) throws Exception {
        DecodeParameterVo decodeParameterVo = new DecodeParameterVo();
        String h5Str = encryptDto.getEncryptStr().replace(" ", "+");
        h5Str = new String(new BASE64Decoder().decodeBuffer(h5Str));
        String[] split = h5Str.split("&&");

        String decodeH5Parameter = CommonUtils.decryptParmByAES(Sns.WEB_TO_API_AES, split[0]);
        decodeParameterVo.setDecodeH5Parameter(decodeH5Parameter);
        if (split.length >= 3){//登录参数没有token
            decodeParameterVo.setToken(split[3]);
        }
        //不能直接返回对象，因为decodeH5Parameter本身就是json传，如果返回对象，会在转成json一次
        //转两次json，json串会多一个双引号
        return decodeParameterVo.toJsonString();
    }

    @ApiOperation(value = "解密商旅返回值")
    @PostMapping(value = "decodeRes", produces = "application/json;charset=utf-8")
    public String decodeRes(@RequestBody EncryptDto encryptDto) throws Exception {
        String aesStr = CommonUtils.decryptParmByAES(Sns.WEB_TO_API_AES, encryptDto.getEncryptStr());
        return aesStr;
    }
}
